<?php
/**
 * 订单
 */

use app\config\Db;
use Core\Result\Result;
use Core\Common\Common;
use Core\Utils\Utils;
use GuzzleHttp\Client;

require_once "Merchant.php";
require_once "MerchantOffline.php";
require_once "Pay.php";

/**
 * 生成订单（单商品） TODO
 * @param $data
 * @return void
 */
function createOrder($data)
{
    $sku_id = $data['sku_id'];
    $order_number = $data['order_number'];
    $address_id = $data['address_id'];
    $remark = $data['remark'];
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    if ($order_number <= 0) Result::error("订单数量错误");
    if ($sku_id <= 0) Result::error("商品不存在");
    $userInfo = $db->find("select `user_id` from `user_info` where `user_id`=$user_id");
    if (!$userInfo) Result::error("用户信息丢失，请重新登录");
    $goodsInfo = $db->find("select gos.*,g.unreal_sales_volume,g.goods_type,g.is_top,g.is_adopt,g.is_task,g.shop_id,g.shipping_method,g.free_shipping,g.goods_type,g.fixed_shipping_fee,g.section_id,g.fixed_shipping_type,g.shipping_tpl_id from ysmz_shop_goods_sku as gos inner join ysmz_shop_goods as g on gos.goods_id=g.goods_id where gos.sku_id=$sku_id limit 1");
    if ($goodsInfo['is_top'] == 0 || $goodsInfo['is_adopt'] == 0) Result::error("商品已下架");
    if ($goodsInfo['sku_stock'] - $order_number < 0) Result::error("库存不足");
    $orderInfo = $db->find("select order_id,order_no,user_id,shop_id,goods_id,sku_id,order_number,order_price,order_total_price,pay_status,shipping_fee,shipping_method,receipt_name,receipt_phone,receipt_address,order_state,order_type from `ysmz_shop_goods_order` where `sku_id` = $sku_id and user_id = $user_id and `order_number` = $order_number and `order_state` = 0 limit 1");

    $addrInfo = $db->find("select * from `receive_address` where `id` = $address_id and `user_id` = $user_id and `data_flag`=1 limit 1");
    if($goodsInfo["goods_type"] == 1){
        if (!$addrInfo) Result::error("收货地址信息错误");
    }
    //if (!$addrInfo) Result::error("收货地址信息错误");
    $receipt_name = $addrInfo['consignee_name'] ?? '';
    $receipt_phone = $addrInfo['consignee_mobile'] ?? '';
    $receipt_address = "{$addrInfo['area_path']}{$addrInfo['detail_address']}";
    $order_no = Utils::createOrderNo("sc");
    $goods_id = $goodsInfo["goods_id"];
    $shop_id = $goodsInfo["shop_id"];
    $order_price = $goodsInfo["sku_sell_price"];//支付价格
    $order_total_price = round($order_price * $order_number,2);
    $pay_status = 1;
    $order_state =0;
    $shipping_method = $goodsInfo["shipping_method"];
    $free_shipping = $goodsInfo["free_shipping"];
    $order_type = $goodsInfo["goods_type"];
    if($free_shipping == 1){//免运费
        $shipping_fee = 0;
    }else{
        if($goodsInfo["fixed_shipping_type"] == 1){
            $shipping_fee = $goodsInfo["fixed_shipping_fee"];//固定运费
        }else{
            $shippingData["order_price"] = $order_price;
            $shippingData["order_number"] = $order_number;
            $shippingData["shipping_tpl_id"] = $goodsInfo["shipping_tpl_id"];
            $shipping_fee = shippingTpl($shippingData);
        }
    }
    $res["paymentMethod"] = getPaymentMethod($db,$goodsInfo["section_id"]);
    $res["coupon"] = CommomCouponList($user_id,$order_total_price,$goods_id);
    if(!empty($orderInfo)){
        $res["orderInfo"] = $orderInfo;
        Result::success($res);
    }
    $addOrderSql = "insert into `ysmz_shop_goods_order`(order_no,user_id,shop_id,goods_id,sku_id,order_number,order_price,order_total_price,pay_status,shipping_fee,shipping_method,receipt_name,receipt_phone,receipt_address,order_state,order_type,`remark`) values ('$order_no',$user_id,$shop_id,$goods_id,$sku_id,$order_number,$order_price,$order_total_price,$pay_status,$shipping_fee,$shipping_method,'$receipt_name','$receipt_phone','$receipt_address',$order_state,$order_type,'$remark')";
    $db->startTrans();
    try {
        if (!$db->save($addOrderSql)) Common::exception("订单添加失败");
        $db->commit();
        $res["orderInfo"] = $db->find("select order_id,order_no,user_id,shop_id,goods_id,sku_id,order_number,order_price,order_total_price,pay_status,shipping_fee,shipping_method,receipt_name,receipt_phone,receipt_address,order_state,order_type from `ysmz_shop_goods_order` where `order_no` = '$order_no' and user_id = $user_id");
        Result::success($res);
    } catch (\Exception $e) {
        // 回滚事务
        $db->rollback();
        Result::error($e->getMessage());
    }
}
/**
 * 生成订单（购物车） TODO
 * @param $data
 * @return void
 */
function createGeneralOrder($data)
{
    $skuInfo = $data['skuInfo'];
    $address_id = $data['address_id'];
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    $skuInfo = json_decode($skuInfo,true);
    $userInfo = $db->find("select `user_id` from `user_info` where `user_id`=$user_id");
    if (!$userInfo) Result::error("用户信息丢失，请重新登录");
    $addrInfo = $db->find("select * from `receive_address` where `id` = $address_id and `user_id` = $user_id and `data_flag`=1 limit 1");
    if (!$addrInfo) Result::error("收货地址信息错误");
    $receipt_name = $addrInfo['consignee_name'];
    $receipt_phone = $addrInfo['consignee_mobile'];
    $receipt_address = "{$addrInfo['area_path']}{$addrInfo['detail_address']}";
    $orderTotalPrice = 0;//父级订单金额
    $shippingFee = 0;//父级订单运费
    $orderNumber = 0;//订单数量
    $pay_status = 1;
    $order_state =0;
    $orderInsertIds ='';
    $shippingTotalFee = [];
    $section_id = 0;
    $db->startTrans();
    try {
        foreach ($skuInfo as $k => $v) {
            $goodsInfo = $db->find("select gos.*,g.unreal_sales_volume,g.section_id,g.goods_type,g.is_top,g.is_adopt,g.is_task,g.shop_id,g.shipping_method,g.free_shipping,g.goods_type,g.fixed_shipping_fee,g.fixed_shipping_type,g.shipping_tpl_id from ysmz_shop_goods_sku as gos inner join ysmz_shop_goods as g on gos.goods_id=g.goods_id where gos.sku_id=$v[sku_id] limit 1");
            $sku_name = $goodsInfo["sku_name"];
            if(empty($goodsInfo)){
                Common::exception("商品不存在");
            }
            $isShipping = false;
            if ($v["order_number"] <= 0) Common::exception($sku_name."商品订单数量错误");
            if ($goodsInfo['is_top'] == 0 || $goodsInfo['is_adopt'] == 0) Common::exception($sku_name."商品已下架");
            if ($goodsInfo['sku_stock'] - $v["order_number"] < 0) Common::exception($sku_name."商品库存不足");
            $order_no = Utils::createOrderNo("sc");
            $goods_id = $goodsInfo["goods_id"];
            $shop_id = $goodsInfo["shop_id"];
            $order_price = $goodsInfo["sku_sell_price"];//支付价格
            $order_total_price = round($order_price * $v["order_number"],2);
            $shipping_method = $goodsInfo["shipping_method"];
            $free_shipping = $goodsInfo["free_shipping"];
            $order_type = $goodsInfo["goods_type"];
            $remark = $v["remark"];
            if($goodsInfo["section_id"] == 2 && in_array($section_id,[0,2])){
                $section_id = $goodsInfo["section_id"];
            }else if($goodsInfo["section_id"] == 6 && in_array($section_id,[0,6])){
                $section_id = $goodsInfo["section_id"];
            }else{
                $section_id = -1;
            }
            if($free_shipping == 1){//免运费
                $shipping_fee = 0;
            }else{
                if($goodsInfo["fixed_shipping_type"] == 1){
                    $shipping_fee = $goodsInfo["fixed_shipping_fee"];//固定运费
                }else{
                    $isShipping = true;
                    $shippingData["order_price"] = $order_price;
                    $shippingData["order_number"] = $v["order_number"];
                    $shippingData["shipping_tpl_id"] = $goodsInfo["shipping_tpl_id"];
                    $shipping_fee = shippingTpl($shippingData);
                    $shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["order_price"] += $order_price*$v["order_number"];
                    $shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["order_number"] = 1;
                    if($shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["shipping_tpl_id"] == $goodsInfo["shipping_tpl_id"] && $shipping_fee >0){
                        $shipping_fee = 0;
                    }
                    $shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["shipping_tpl_id"] = $goodsInfo["shipping_tpl_id"];
                }
            }
            //$res["coupon"] = CommomCouponList($user_id,$order_total_price,$goods_id);//优惠券查询
            $orderTotalPrice += $order_total_price;
            $shippingFee += $shipping_fee;
            $orderNumber++;
            $addOrderSql = "insert into `ysmz_shop_goods_order`(order_no,user_id,shop_id,goods_id,sku_id,order_number,order_price,order_total_price,pay_status,shipping_fee,shipping_method,receipt_name,receipt_phone,receipt_address,order_state,order_type,remark) values ('$order_no',$user_id,$shop_id,$goods_id,$v[sku_id],$v[order_number],$order_price,$order_total_price,$pay_status,$shipping_fee,$shipping_method,'$receipt_name','$receipt_phone','$receipt_address',$order_state,$order_type,'$remark')";
            if (!$db->save($addOrderSql)) Common::exception("订单添加失败");
            $mysql_insert_id = $db->mysql_insert_id();
            if($isShipping && $shipping_fee > 0 ){
                $shippingTotalFee[$goodsInfo["shipping_tpl_id"]]["ids"] .= $mysql_insert_id.',';
            }
            $orderInsertIds .= $mysql_insert_id.',';
            //删除购物车
            $delCart = "delete from `ysmz_cart` where `user_id` =$user_id and `cart_id` = $v[cart_id]";
            if (!$db->save($delCart)) Common::exception("购物车不存在的商品");
        }
        $orderId = mb_substr($orderInsertIds, 0, -1);
        if($orderNumber > 1){
            foreach ($shippingTotalFee as $k => $v) {
                $v["shipping_tpl_id"] = $k;
                $shippingTpl = shippingTpl($v);
                if($shippingTpl == 0){
                    if(!empty($v["ids"])){
                        $orderIds = mb_substr($v["ids"], 0, -1);
                        $totalShipping = $db->find("select sum(shipping_fee) as shippingFee from `ysmz_shop_goods_order` where `order_id` in($orderIds) and user_id = $user_id");
                        $upOrderFee = "update `ysmz_shop_goods_order` set `shipping_fee` = 0 where `order_id` in($orderIds) and `user_id`=$user_id and  `shipping_fee` > 0";
                        if (!$db->save($upOrderFee)) Common::exception("更新订单运费失败");
                        $shippingFee -= $totalShipping["shippingFee"];
                    }
                }
            }
            $order_no = Utils::createOrderNo("sc");
            $addParentOrderSql = "insert into `ysmz_shop_goods_order`(order_no,user_id,is_parent,order_total_price,pay_status,shipping_fee,receipt_name,receipt_phone,receipt_address,order_state,order_type) values ('$order_no',$user_id,1,$orderTotalPrice,$pay_status,$shippingFee,'$receipt_name','$receipt_phone','$receipt_address',$order_state,$order_type)";
            if (!$db->save($addParentOrderSql)) Common::exception("父级订单添加失败");
            $parentId = $db->mysql_insert_id();

            //绑定子订单
            $upOrder = "update `ysmz_shop_goods_order` set `parent_order_id` = $parentId where `order_id` in($orderId) and `user_id`=$user_id";
            if (!$db->save($upOrder)) Common::exception("绑定订单失败");
            $res["orderInfo"] = $db->find("select order_id,order_no,user_id,shop_id,goods_id,sku_id,order_number,order_price,order_total_price,pay_status,shipping_fee,shipping_method,receipt_name,receipt_phone,receipt_address,order_state,order_type from `ysmz_shop_goods_order` where `order_no` = '$order_no' and user_id = $user_id");
        }else{
            $res["orderInfo"] = $db->find("select order_id,order_no,user_id,shop_id,goods_id,sku_id,order_number,order_price,order_total_price,pay_status,shipping_fee,shipping_method,receipt_name,receipt_phone,receipt_address,order_state,order_type from `ysmz_shop_goods_order` where `order_id` = '$orderId' and user_id = $user_id");
        }
        $db->commit();
    } catch (\Exception $e) {
        // 回滚事务
        $db->rollback();
        Result::error($e->getMessage());
    }
    $res["paymentMethod"] = getPaymentMethod($db,$section_id);
    Result::success($res);
}
/**
 * 获取可用支付方式 TODO
 * @param $db
 * @return array
 */
function getPaymentMethod($db,$type=0)
{
    $sql="select `name`,`value`,`server_name`,`desc` from `mall_config` where `business` = 'pay' and `status` =0 and `type` in(0,$type)";
    return $db->query($sql);
}
/**
 * 获取可用优惠券 TODO
 * @param $data
 * @return array
 */
function CommomCouponList($user_id,$money=0,$goods_id=0)
{
    $time = time();
    $db = new Db();
    $where = " and `order_id` =0 and `start_date` < $time and `end_date` > $time";//可用优惠券
    $userCouponInfo = $db->query("select `id`,`coupon_id`,`coupon_sn`,`used_time`,`order_id`,`start_date`,`end_date` from `user_coupon` where `user_id` = $user_id $where");
    $list =[];
    foreach ($userCouponInfo as $k => $v) {
        $userCouponInfo[$k]["start_date"] = date("Y-m-d H:i:s",$v["start_date"]);
        $userCouponInfo[$k]["end_date"] = date("Y-m-d H:i:s",$v["end_date"]);
        $couponInfo = $db->find("select `coupon_name`,`coupon_money`,`coupon_discount`,`coupon_desc`,`coupon_type`,`send_range`,`min_order_amount`,`max_order_amount`,`coupon_unit`,`reduce_type` from `ysmz_coupon` where `coupon_id` = $v[coupon_id]");
        if($money < $couponInfo["min_order_amount"]){
            unset($userCouponInfo[$k]);
            unset($couponInfo);
        }
        switch ($couponInfo["send_range"]){
            case 3:
                $explode = explode(",", $couponInfo["send_range_data"]);
                if(!in_array($goods_id, $explode)){
                    unset($userCouponInfo[$k]);
                    unset($couponInfo);
                }
                break;
            case 4:
                $explode = explode(",", $couponInfo["send_range_data"]);
                if(in_array($goods_id, $explode)){
                    unset($userCouponInfo[$k]);
                    unset($couponInfo);
                }
                break;
        }
        if(!empty($couponInfo)){
            $list = array_merge_recursive($userCouponInfo[$k], $couponInfo);
        }

    }
    return $list;
}
/**
 * 订单列表 TODO
 * @param $data
 * @return void
 */
function orderList($data)
{
    $page  = $data['page'];
    $limit  = $data['limit'];
    $order_state  = $data['order_state'];
    $comment_status  = $data['comment_status'];
    $user_id = Common::getUser_id($data);
    if(!empty($order_state)){
        $is_parent = "and `is_parent` = 0";
    }else{
        $is_parent = " AND IF(order_state <> 0, is_parent = 0, `parent_order_id` = 0) ";
    }
    $where = " user_id = $user_id and is_delete = 0 $is_parent";
    if ($order_state > -1) $where .= " and `order_state` = $order_state";
    if ($comment_status > -1) $where .= " and `order_state` = 3 and `comment_status` = $comment_status";
    $order = "order by `create_time` desc";
    if(in_array($order_state,[1,2,3])){
        $order = "order by `pay_time` desc";
    }
    $field = 'order_id,order_no,user_id,is_parent,parent_order_id,shop_id,goods_id,sku_id,order_number,order_price,order_total_price,order_coupon_price,shipping_fee,payment_type,pay_status,shipping_method,order_state,logistics_name,logistics_no,remark,create_time,order_type,receipt_name,receipt_phone,receipt_address,order_pay_price,comment_status';
    $db = new Db("host");
    $orderInfo = $db->query("select $field from `ysmz_shop_goods_order` where $where $order limit $page,$limit");
    if (!$orderInfo) Result::success();
    $goodsIds = implode(',', array_column($orderInfo, 'goods_id'));
    $goodsSkuIds = implode(',', array_column($orderInfo, 'sku_id'));
    $goodsInfo = $db->query("select `goods_id`,`name`,`free_shipping`,`fixed_shipping_fee`,`section_id`,`shipping_tpl_id` from `ysmz_shop_goods` where `goods_id` in($goodsIds)", 'goods_id');
    $SkuInfo = $db->query("select `sku_id`,`sku_name`,`sku_img_id`,`spec_info` from `ysmz_shop_goods_sku` where sku_id in($goodsSkuIds)", 'sku_id');
    $fileId = implode(',', array_column($SkuInfo, 'sku_img_id'));
    $fileInfo = $db->query("select file_id,storage,`domain`,file_path from ysmz_file where file_id in($fileId)");
    foreach ($fileInfo as $k => $v) {
        $fileInfo[$k]['file_url'] = Common::fileUrl($v);
    }
    $fileInfo = array_column($fileInfo, 'file_url', 'file_id');
    foreach ($SkuInfo as $k => $v) {
        $SkuInfo[$k]['sku_img_url'] = $fileInfo[$v['sku_img_id']] ?? '';
    }
    foreach ($orderInfo as $k => $v) {
        if($v["is_parent"] == 1 && ($v["order_state"] == 0 || $v["order_state"] == 4)){
            $childOrderInfo = $db->query("select $field from `ysmz_shop_goods_order` where `user_id` = $user_id and `parent_order_id`=$v[order_id]  $order");
            $goodsIds = implode(',', array_column($childOrderInfo, 'goods_id'));
            $goodsSkuIds = implode(',', array_column($childOrderInfo, 'sku_id'));
            $childGoodsInfo = $db->query("select `goods_id`,`name`,`free_shipping`,`fixed_shipping_fee`,`section_id`,`shipping_tpl_id` from `ysmz_shop_goods` where `goods_id` in($goodsIds)", 'goods_id');
            $childSkuInfo = $db->query("select `sku_id`,`sku_name`,`sku_img_id`,`spec_info` from `ysmz_shop_goods_sku` where sku_id in($goodsSkuIds)", 'sku_id');
            $fileId = implode(',', array_column($childSkuInfo, 'sku_img_id'));
            $fileInfo = $db->query("select file_id,storage,`domain`,file_path from ysmz_file where file_id in($fileId)");
            foreach ($fileInfo as $kk => $vv) {
                $fileInfo[$kk]['file_url'] = Common::fileUrl($vv);
            }
            $fileInfo = array_column($fileInfo, 'file_url', 'file_id');
            foreach ($childSkuInfo as $kk => $vv) {
                $childSkuInfo[$kk]['sku_img_url'] = $fileInfo[$vv['sku_img_id']] ?? '';
            }
            $section_id = 0;
            foreach ($childOrderInfo as $k1 => $v1) {
                if($childGoodsInfo[$v1['goods_id']]["section_id"] == 2 && in_array($section_id,[0,2])){
                    $section_id = $childGoodsInfo[$v1['goods_id']]["section_id"];
                }else if($childGoodsInfo[$v1['goods_id']]["section_id"] == 6 && in_array($section_id,[0,6])){
                    $section_id = $childGoodsInfo[$v1['goods_id']]["section_id"];
                }else{
                    $section_id = -1;
                }
                $childOrderInfo[$k1]["free_shipping"] = $childGoodsInfo[$v1['goods_id']]['free_shipping'];
                $childOrderInfo[$k1]["fixed_shipping_fee"] = $childGoodsInfo[$v1['goods_id']]['fixed_shipping_fee'];
                $childOrderInfo[$k1]['goods_name'] = $childGoodsInfo[$v1['goods_id']]['name'] ?? '';
                $childOrderInfo[$k1]['sku'] = $childSkuInfo[$v1['sku_id']] ?? [];
                if($childSkuInfo[$v['sku_id']]['spec_info']){
                    $订单规格ID = implode(',', json_decode($childSkuInfo[$v['sku_id']]['spec_info'], true));
                    $订单规格信息 = $db->query("select spec_id,name from ysmz_shop_goods_spec where spec_id in($订单规格ID)");
                    $订单规格信息 = implode(',', array_column($订单规格信息, 'name'));
                    $childOrderInfo[$k]['sku']['spec_name'] = $订单规格信息;
                    $childOrderInfo[$k]['spec_name'] = $订单规格信息;
                }

            }
            $orderInfo[$k]["childOrder"] = $childOrderInfo;
            $orderInfo[$k]["paymentMethod"] = getPaymentMethod($db,$section_id);
            $orderInfo[$k]["coupon"] = [];
            $orderInfo[$k]["merchantOfflineCount"] = 0;
        }else{
            $orderInfo[$k]["free_shipping"] = $goodsInfo[$v['goods_id']]['free_shipping'];
            $orderInfo[$k]["fixed_shipping_fee"] = $goodsInfo[$v['goods_id']]['fixed_shipping_fee'];
            $orderInfo[$k]['goods_name'] = $goodsInfo[$v['goods_id']]['name'] ?? '';
            $orderInfo[$k]['sku'] = $SkuInfo[$v['sku_id']] ?? [];
            if($SkuInfo[$v['sku_id']]['spec_info']){
                $订单规格ID = implode(',', json_decode($SkuInfo[$v['sku_id']]['spec_info'], true));
                $订单规格信息 = $db->query("select spec_id,name from ysmz_shop_goods_spec where spec_id in($订单规格ID)");
                $订单规格信息 = implode(',', array_column($订单规格信息, 'name'));
                $orderInfo[$k]['sku']['spec_name'] = $订单规格信息;
                $orderInfo[$k]['spec_name'] = $订单规格信息;
            }
            $orderInfo[$k]["paymentMethod"] = getPaymentMethod($db,$goodsInfo[$v['goods_id']]['section_id']);
            $orderInfo[$k]["coupon"] = CommomCouponList($user_id,$orderInfo["order_total_price"],$orderInfo["goods_id"]);
            $orderInfo[$k]["merchantOfflineCount"] = merchantCount($v);
        }
    }
    Result::success($orderInfo);
}
/**
 * 订单信息 TODO
 * @param $userTokenInfo
 * @return void
 */
function orderInfo($data)
{
    $order_id = $data["order_id"];
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $orderInfo = $db->find("select * from `ysmz_shop_goods_order` where `order_id`=$order_id and `user_id`=$user_id and `is_delete`=0 limit 1");
    if (!$orderInfo) Result::error("订单信息不存在");
    if($orderInfo["is_parent"] == 1){
        $childOrderInfo = $db->query("select * from `ysmz_shop_goods_order` where `parent_order_id`=$order_id and `user_id`=$user_id and `is_delete`=0");
        $section_id = 0;
        foreach ($childOrderInfo as $kk => $vv) {
            $goodsInfo = $db->find("select goods_id,name,free_shipping,fixed_shipping_fee,section_id,shop_id,`section_id` from `ysmz_shop_goods` where `goods_id`={$vv['goods_id']} limit 1");
            if($goodsInfo["section_id"] == 2 && in_array($section_id,[0,2])){
                $section_id = $goodsInfo["section_id"];
            }else if($goodsInfo["section_id"] == 6 && in_array($section_id,[0,6])){
                $section_id = $goodsInfo["section_id"];
            }else{
                $section_id = -1;
            }
            $SkuInfo = $db->find("select sku_id,sku_name,sku_img_id,spec_info from `ysmz_shop_goods_sku` where sku_id={$vv['sku_id']} limit 1");
            if(empty($goodsInfo) || empty($SkuInfo)){
                Result::error("订单商品信息不存在");
            }
            $fileInfo = $db->find("select file_id,storage,`domain`,file_path from ysmz_file where file_id={$SkuInfo['sku_img_id']} limit 1");
            $SkuInfo['sku_img_url'] = Common::fileUrl($fileInfo);
            $spec = implode(',', json_decode($SkuInfo['spec_info'], true));
            $specInfo = $db->query("select spec_id,name from ysmz_shop_goods_spec where spec_id in($spec)");
            $specInfo = implode(',', array_column($specInfo, 'name'));
            $childOrderInfo[$kk]['spec_name'] = $specInfo;
            $childOrderInfo[$kk]['goods'] = $goodsInfo;
            $childOrderInfo[$kk]['sku'] = $SkuInfo;
            $childOrderInfo[$kk]['free_shipping'] = $goodsInfo["free_shipping"];
            $childOrderInfo[$kk]['fixed_shipping_fee'] = $goodsInfo["fixed_shipping_fee"];
            $childOrderInfo[$kk]["coupon"] = CommomCouponList($user_id,$childOrderInfo["order_total_price"],$childOrderInfo["goods_id"]);
            $childOrderInfo[$kk]["kefu_phone"] = queryShopInfo($goodsInfo["shop_id"],2)["kefu_phone"];
            $childOrderInfo[$kk]["merchantOfflineCount"] = merchantCount($orderInfo);
            $childOrderInfo[$kk]["merchant_name"] = '';
            if($childOrderInfo["merchant_id"]){
                $offlineInfo = $db->find("SELECT `merchant_name` FROM `ysmz_merchant_offline` WHERE `merchant_id` = $orderInfo[merchant_id] and `shop_id` = $orderInfo[shop_id]");
                $childOrderInfo["merchant_name"] = $offlineInfo["merchant_name"];
            }
            $orderInfo["childOrder"] = $childOrderInfo;
        }
        $orderInfo["merchant_name"] = '';
        $orderInfo["paymentMethod"] = getPaymentMethod($db,$section_id);
        Result::success($orderInfo);
    }
    $goodsInfo = $db->find("select goods_id,name,free_shipping,fixed_shipping_fee,section_id,shop_id from `ysmz_shop_goods` where `goods_id`={$orderInfo['goods_id']} limit 1");
    $SkuInfo = $db->find("select sku_id,sku_name,sku_img_id,spec_info from `ysmz_shop_goods_sku` where sku_id={$orderInfo['sku_id']} limit 1");
    if(empty($goodsInfo) || empty($SkuInfo)){
        Result::error("订单商品信息不存在");
    }
    $fileInfo = $db->find("select file_id,storage,`domain`,file_path from ysmz_file where file_id={$SkuInfo['sku_img_id']} limit 1");
    $SkuInfo['sku_img_url'] = Common::fileUrl($fileInfo);
    $spec = implode(',', json_decode($SkuInfo['spec_info'], true));
    $specInfo = $db->query("select spec_id,name from ysmz_shop_goods_spec where spec_id in($spec)");
    $specInfo = implode(',', array_column($specInfo, 'name'));
    $orderInfo['spec_name'] = $specInfo;
    $orderInfo['goods'] = $goodsInfo;
    $orderInfo['sku'] = $SkuInfo;
    $orderInfo['free_shipping'] = $goodsInfo["free_shipping"];
    $orderInfo['fixed_shipping_fee'] = $goodsInfo["fixed_shipping_fee"];
    $orderInfo["paymentMethod"] = getPaymentMethod($db,$goodsInfo["section_id"]);
    $orderInfo["coupon"] = CommomCouponList($user_id,$orderInfo["order_total_price"],$orderInfo["goods_id"]);
    $orderInfo["kefu_phone"] = queryShopInfo($goodsInfo["shop_id"],2)["kefu_phone"];
    $orderInfo["merchantOfflineCount"] = merchantCount($orderInfo);
    $orderInfo["merchant_name"] = '';
    if($orderInfo["merchant_id"]){
        $offlineInfo = $db->find("SELECT `merchant_name` FROM `ysmz_merchant_offline` WHERE `merchant_id` = $orderInfo[merchant_id] and `shop_id` = $orderInfo[shop_id]");
        $orderInfo["merchant_name"] = $offlineInfo["merchant_name"];
    }
    Result::success($orderInfo);
}
/**
 * 门店选择 TODO
 * @param $data
 * @return void
 */
function storeSelection($data)
{
    $longitude  = $data['longitude'];
    $latitude  = $data['latitude'];
    $order_id = $data["order_id"];
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $orderInfo = $db->find("select `order_id`,`shop_id` from `ysmz_shop_goods_order` where `order_id`=$order_id and `user_id`=$user_id and `is_delete`=0 limit 1");
    if (!$orderInfo) Result::error("订单信息不存在");
    $data["shop_id"] = $orderInfo["shop_id"];
    $merchantOrderList = merchantOrderList($data);
    Result::success($merchantOrderList);
}
/**
 * 门店绑定 TODO
 * @param $data
 * @return void
 */
function storeBindingSelection($data)
{
    $merchant_id  = $data['merchant_id'];
    $order_id  = $data['order_id'];
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $orderInfo = $db->find("select `order_id`,`shop_id`,`merchant_id`,`order_state`,`shipping_status`,`pay_no`,`openid`,`goods_id` from `ysmz_shop_goods_order` where `order_id`=$order_id and `user_id`=$user_id and `is_delete`=0 limit 1");
    if (!$orderInfo) Result::error("订单信息不存在");
    if($merchant_id == $orderInfo["merchant_id"] && $orderInfo["order_state"] == 2){
        Result::success("ok");
    }
    $offlineInfo = $db->find("SELECT count(merchant_id) as count FROM `ysmz_merchant_offline` WHERE `merchant_id` = $merchant_id and `shop_id` = $orderInfo[shop_id] and `state` = 1");
    if($offlineInfo["count"] <=0){
        Result::error("非关联门店，请核对订单");
    }
    if($orderInfo["order_state"] == 1 && $orderInfo["pay_no"] && $orderInfo["openid"]){
        $goodsInfo = $db->find("select `name` from `ysmz_shop_goods` where `goods_id`=$orderInfo[goods_id]");
        $shippingData["out_trade_no"] = $orderInfo["pay_no"];
        $shippingData["item_desc"] = $goodsInfo["name"];
        $shippingData["logistics_type"] = 4;
        $shippingData["openid"] = $orderInfo["openid"];
        $uploadShippingInfo = uploadShippingInfo($shippingData);
        if($uploadShippingInfo["errcode"] != 0){
            $content = "微信发货通知失败=>错误代码：".$uploadShippingInfo["errcode"].",错误原因：".$uploadShippingInfo["errmsg"]."单号：".$shippingData["out_trade_no"].",时间：".date("Y-m-d H:i:s",time());
            Utils::writePayLog($content);
        }
    }
    // 启动事务
    $db->startTrans();
    try {
        $upOrder = "update `ysmz_shop_goods_order` set `merchant_id` = $merchant_id,`order_state` = 2 ,`shipping_status` = 1 where `order_id`=$order_id and `order_state`={$orderInfo['order_state']}";
        if (!$db->save($upOrder)) Common::exception("订单门店更新错误");
        // 提交事务
        $db->commit();
        Result::success("ok");
    } catch (\Exception $e) {
        // 回滚事务
        $db->rollback();
        Result::error($e->getMessage() . '失败');
    }
}
/**
 * 订单修改 TODO
 * @param $data
 * @return void
 */
function orderEdit($data)
{
    $order_id = $data["order_id"];
    $edit_type = $data["edit_type"];
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    $orderInfo = $db->find("select order_id,order_state,order_type from `ysmz_shop_goods_order` where order_id=$order_id and `user_id` = $user_id");
    if (!$orderInfo) Result::error("订单信息不存在");
    // 启动事务
    $db->startTrans();
    try {
        switch ($edit_type) {
            case 1://确认收货
                if ($orderInfo['order_state'] != 2) Result::error("订单未发货，无法确认收货！");
                if ($orderInfo['order_type'] != 1) Result::error("虚拟商品，无法确认收货！");
                $received_time = date("Y-m-d H:i:s",time());
                $upJoin = " order_state = 3 ,shipping_status = 2 ,received_time = '$received_time'";
                $info = '确认收货';
                break;
            default:
                Common::exception('非法修改类型');
        }
        $upOrder = "update `ysmz_shop_goods_order` set $upJoin where `order_id`=$order_id and `order_state`={$orderInfo['order_state']}";
        if (!$db->save($upOrder)) Common::exception("$info"."失败");
        // 提交事务
        $db->commit();
        Result::success($info."成功");
    } catch (\Exception $e) {
        // 回滚事务
        $db->rollback();
        Result::error($e->getMessage() . '失败');
    }
}
/**
 * 订单取消 TODO
 * @param $data
 * @return void
 */
function cancelDele($data)
{
    $order_id = $data["order_id"];
    $time = time();
    $datetime = date('Y-m-d H:i:s', $time);
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    $orderInfo = $db->find("select `order_state`,`is_parent` from `ysmz_shop_goods_order` where `order_id`=$order_id and `user_id`=$user_id limit 1");
    if (!$orderInfo) Result::error("订单信息不存在");
    if ($orderInfo['order_state'] != 0) Result::error("订单状态不可取消");
    $delOrder = "update `ysmz_shop_goods_order` set order_state=4,update_time='$datetime' where `order_id`=$order_id";
    $db->startTrans();
    try {
        if (!$db->save($delOrder)) Common::exception("订单取消失败");
        if($orderInfo["is_parent"] == 1){
            $delChildOrder = "update `ysmz_shop_goods_order` set order_state=4,update_time='$datetime' where `parent_order_id`=$order_id and `user_id`=$user_id";
            if (!$db->save($delChildOrder)) Common::exception("子订单取消失败");
        }
        $db->commit();
        Result::success("订单取消成功");
    } catch (\Exception $e) {
        // 回滚事务
        $db->rollback();
        Result::error($e->getMessage());
    }
}
/**
 * 订单删除 TODO
 * @param $data
 * @return void
 */
function orderDele($data)
{
    $order_id = $data["order_id"];
    $time = time();
    $datetime = date('Y-m-d H:i:s', $time);
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    $orderInfo = $db->find("select `order_state`,`is_parent` from `ysmz_shop_goods_order` where `order_id`=$order_id and `user_id`=$user_id limit 1");
    if (!$orderInfo) Result::error("订单信息不存在");
    if ($orderInfo['order_state'] < 2 ) Result::error("订单状态不可删除");
    $delOrder = "update `ysmz_shop_goods_order` set is_delete=1,delete_time='$datetime' where `order_id`=$order_id";
    $db->startTrans();
    try {
        if (!$db->save($delOrder)) Common::exception("订单删除失败");
        if($orderInfo["is_parent"] == 1){
            $delChildOrder = "update `ysmz_shop_goods_order` set is_delete=1,delete_time='$datetime' where `parent_order_id`=$order_id and `user_id`=$user_id";
            if (!$db->save($delChildOrder)) Common::exception("子订单删除失败");
        }
        $db->commit();
        Result::success("订单删除成功");
    } catch (\Exception $e) {
        // 回滚事务
        $db->rollback();
        Result::error($e->getMessage());
    }
}
/**
 * 订单评价 TODO
 * @param $data
 * @return void
 */
function orderComment($data)
{
    $order_id = $data["order_id"];
    $star = $data["star"];
    $comment = $data["comment"];
    $img_url = $data["img_url"];
    if(empty($star) || $star > 5 || $star <=0){
        Result::error("请评分1-5分");
    }
    $time = time();
    $datetime = date('Y-m-d H:i:s', $time);
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    $orderInfo = $db->find("select `goods_id`,`order_state`,`comment_status` from `ysmz_shop_goods_order` where `order_id`=$order_id and `user_id`=$user_id limit 1");
    if (!$orderInfo) Result::error("订单信息不存在");
    if ($orderInfo['order_state'] != 3) Result::error("订单状态不可评价");
    if ($orderInfo['comment_status'] == 1) Result::error("订单已评价");
    $addReviewsSql = "insert into `ysmz_goods_reviews`(g_id,o_id,user_id,star,comment,img_url) values ($orderInfo[goods_id],$order_id,$user_id,$star,'$comment','$img_url')";
    $upOrder = "update `ysmz_shop_goods_order` set comment_status=1,update_time='$datetime' where `order_id`=$order_id";
    $db->startTrans();
    try {
        if (!$db->save($addReviewsSql)) Common::exception("订单评价失败");
        if (!$db->save($upOrder)) Common::exception("订单修改失败");
        $db->commit();
        Result::success();
    } catch (\Exception $e) {
        // 回滚事务
        $db->rollback();
        Result::error($e->getMessage());
    }
}
/**
 * 已评价列表 TODO
 * @param $data
 * @return void
 */
function commentList($data)
{
    $page  = $data['page'];
    $limit  = $data['limit'];
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $reviewsInfo = $db->query("select gr.id,`star`,`comment`,`img_url`,`goods_id`,gr.create_date,`name`,`img_id` from `ysmz_goods_reviews` as gr inner join `ysmz_shop_goods` as sg on gr.g_id = sg.goods_id where gr.`user_id`=$user_id and gr.state = 1 order by gr.`create_date` desc limit $page,$limit");
    foreach ($reviewsInfo as $item => $value){
        $fileInfo = $db->find("select file_id,storage,`domain`,file_path from ysmz_file where file_id in($value[img_id])");
        $reviewsInfo[$item]['goods_img'] = Common::fileUrl($fileInfo);
    }
    Result::success($reviewsInfo);
}
/**
 * 订单评论删除 TODO
 * @param $data
 * @return void
 */
function orderDeleReviews($data)
{
    $id = $data["id"];
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    $Info = $db->find("select `state` from `ysmz_goods_reviews` where `id`=$id and `user_id`=$user_id limit 1");
    if (!$Info) Result::error("评论信息不存在");
    if ($Info['state'] != 1) Result::error("评论已删除");
    $delReviews = "update `ysmz_goods_reviews` set state = -1 where `id`=$id";
    if (!$db->save($delReviews)) Result::error("评论删除失败");
    Result::success("评论删除成功");
}
/**
 * 订单count TODO
 * @param $data
 * @return void
 * @throws \think\Exception
 */
function orderCount($data)
{
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $orderInfo = $db->query("SELECT states.order_state,COUNT(o.order_id) AS count FROM (SELECT 0 AS order_state UNION ALL SELECT 1 AS order_state UNION ALL SELECT 2 AS order_state) AS states LEFT JOIN `ysmz_shop_goods_order` o ON states.order_state = o.order_state AND o.user_id = $user_id AND o.is_delete = 0 AND o.is_parent = 0 GROUP BY states.order_state ORDER BY states.order_state");
    $aftersalesInfo = $db->query("SELECT 'order_state',COUNT(aftersale_id) AS count FROM `ysmz_aftersales` where user_id = $user_id AND status in(1,2,3,4,5)");
    $aftersalesInfo[0]["order_state"] = '3';
    $res = array_merge_recursive($orderInfo,$aftersalesInfo);
    Result::success($res);
}
/**
 * 订单物流信息 TODO
 * @param $data
 * @return void
 * @throws \think\Exception
 */
function expressInfo($data)
{
    $order_id = $data["order_id"];
    $type = $data["type"];
    $user_id = Common::getUser_id($data);
    $db = new Db("host");
    $orderInfo = $db->find("select order_state,logistics_info,logistics_number,logistics_no,receipt_phone from `ysmz_shop_goods_order` where order_id=$order_id and user_id = $user_id");
    if(empty($orderInfo["logistics_no"])){
        Result::error("未查询到物流信息");
    }
    if($orderInfo["logistics_number"] >= 20){
        Result::error("触发天级流控，请明日再试");
    }
    $host = "https://kzexpress.market.alicloudapi.com";
    $path = "/api-mall/api/express/query";
    $appcode = "0a2286f6d2254e74a4133bc8e3cef016";
    $headers = [
        "Authorization" => "APPCODE " . $appcode,
        "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"
    ];
    $bodys = "expressNo=$orderInfo[logistics_no]&mobile=$orderInfo[receipt_phone]";
    $url = $host . $path;
    $client = new Client();
    $response = $client->post($url, [
        'headers' => $headers,
        'body' => $bodys
    ]);
    $statusCode = $response->getStatusCode();
    if($statusCode == 200){
        $content = $response->getBody()->getContents();
        $json_decode = json_decode($content, true);
        $upLogisticsNumber = "update `ysmz_shop_goods_order` set logistics_number = logistics_number+1 where `order_id`=$order_id";
        if (!$db->save($upLogisticsNumber)) Result::error("更新订单失败");
        Result::success($json_decode["data"]);
    }
    Result::error("未查询到物流信息");
}
/**
 * 获取运费 TODO
 * @param $data
 * @return void
 * @throws \think\Exception
 */
function queryShippingFee($data)
{
    $sku_id = $data['sku_id'];
    $order_number = $data['order_number'];
    $db = new Db();
    if ($order_number <= 0) Result::error("订单数量错误");
    if ($sku_id <= 0) Result::error("商品不存在");
    $goodsInfo = $db->find("select gos.*,g.unreal_sales_volume,g.goods_type,g.is_top,g.is_adopt,g.is_task,g.shop_id,g.shipping_method,g.free_shipping,g.goods_type,g.fixed_shipping_fee,g.section_id,g.fixed_shipping_type,g.shipping_tpl_id from ysmz_shop_goods_sku as gos inner join ysmz_shop_goods as g on gos.goods_id=g.goods_id where gos.sku_id=$sku_id limit 1");
    if (empty($goodsInfo)) Result::error("商品不存在");
    $free_shipping = $goodsInfo["free_shipping"];
    if($free_shipping == 1){//免运费
        $shipping_fee = '0';
    }else{
        if($goodsInfo["fixed_shipping_type"] == 1){
            $shipping_fee = ''.$goodsInfo["fixed_shipping_fee"];//固定运费
        }else{
            $shippingData["order_price"] = $goodsInfo["sku_sell_price"];
            $shippingData["order_number"] = $order_number;
            $shippingData["shipping_tpl_id"] = $goodsInfo["shipping_tpl_id"];
            $shipping_fee = shippingTpl($shippingData).'';
        }
    }
    exit(json_encode(array(
        "code"=>200,
        "msg"=>"成功",
        "data"=>$shipping_fee
    ),JSON_UNESCAPED_UNICODE));
}
function shippingTpl($data)
{
    $shipping_tpl_id = $data["shipping_tpl_id"];
    $order_price = $data["order_price"];
    $order_number = $data["order_number"];
    $total_price = $order_price * $order_number;
    $db = new Db();
    $shippingInfo = $db->find("select shipping_time,start_number,start_price,add_number,add_price,sti.free_price,sti.pricing_type from `ysmz_shipping_tpl` as st inner join `ysmz_shipping_tpl_info` as sti on st.shipping_tpl_id = sti.shipping_tpl_id where st.`shipping_tpl_id` = $shipping_tpl_id");
    if($total_price >= $shippingInfo["free_price"]){
        return 0;
    }
    $number = $data["order_number"] - $shippingInfo["start_number"];
    if($number <= 0){
        return $shippingInfo["start_price"];
    }
    if($shippingInfo["add_number"] > 0){
        $addNumber = ceil($number / $shippingInfo["add_number"]);
        return $shippingInfo["start_price"] + $addNumber * $shippingInfo["add_price"];
    }
    return $shippingInfo["start_price"];
}